using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Beauty.Net.RabbitMQ
{
    /// <summary>
    /// RabbitMQ依赖注入扩展
    /// </summary>
    public static class RabbitMQExtensions
    {
        /// <summary>
        /// 添加RabbitMQ服务（使用配置委托）
        /// </summary>
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services, Action<RabbitMQOptions> configureOptions)
        {
            var options = new RabbitMQOptions();
            configureOptions(options);
            services.AddSingleton(options);

            // 注册连接管理器
            services.AddSingleton<IRabbitMQConnectionManager, RabbitMQConnectionManager>();

            // 注册各种模式的生产者
            services.AddSingleton<SimpleQueue.SimpleQueueProducer>();
            services.AddSingleton<WorkQueue.WorkQueueProducer>();
            services.AddSingleton<PublishSubscribe.PublishSubscribeProducer>();
            services.AddSingleton<Routing.RoutingProducer>();
            services.AddSingleton<Topic.TopicProducer>();
            services.AddSingleton<Headers.HeadersProducer>();

            // 注册通用生产者接口
            services.AddSingleton<IRabbitMQProducer>(provider => provider.GetRequiredService<SimpleQueue.SimpleQueueProducer>());

            return services;
        }

        /// <summary>
        /// 注册消费者服务（作用域或单例）
        /// </summary>
        public static IServiceCollection AddRabbitMQConsumer<TService, TImplementation>(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton)
            where TImplementation : class, TService
            where TService : class, IRabbitMQConsumer
        {
            switch (lifetime)
            {
                case ServiceLifetime.Singleton:
                    services.AddSingleton<TService, TImplementation>();
                    break;
                case ServiceLifetime.Scoped:
                    services.AddScoped<TService, TImplementation>();
                    break;
                case ServiceLifetime.Transient:
                    services.AddTransient<TService, TImplementation>();
                    break;
            }

            return services;
        }

        /// <summary>
        /// 启动所有已注册的消费者
        /// </summary>
        public static IApplicationBuilder UseRabbitMQConsumers(this IApplicationBuilder app)
        {
            var consumers = app.ApplicationServices.GetServices<IRabbitMQConsumer>();
            foreach (var consumer in consumers)
            {
                consumer.Start();
            }
            return app;
        }
    }
}